package com.example.demo.thread;

import java.text.SimpleDateFormat;
import java.util.Random;

/**
 * @Description:
 * @Author: xiatian
 * @CreateTime: 2021/7/28
 * @Company: kangxu
 */
public class ThreadlocalDemo implements Runnable {


    private static final ThreadLocal<SimpleDateFormat> format = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyyMMdd HHmm"));

    public static void main(String[] args) throws InterruptedException {
        ThreadlocalDemo threadlocal = new ThreadlocalDemo();
        for (int i = 0; i < 10; i++) {
            Thread t = new Thread(threadlocal, "" + i);
            Thread.sleep(new Random().nextInt(1000));
            t.start();
        }
    }

    @Override
    public void run() {
        System.out.println("Thread name=" + Thread.currentThread().getName() + " default Formatter=" + format.get().toPattern());
        try {
            Thread.sleep(new Random().nextInt(1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        format.set(new SimpleDateFormat());
        System.out.println("Thread name=" + Thread.currentThread().getName() + " default Formatter=" + format.get().toPattern());
    }
}
